﻿using System;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace Helper
{
    public interface IRunner
    {
        /// <summary>
        /// 加载程序相关配置文件 *.ini
        /// </summary>
        /// <param name="filename"></param>
        void LoadConfig(string filename);

        /// <summary>
        /// 运行程序
        /// </summary>
        /// <param name="globalConfigData">全局配置(Config.txt)</param>
        /// <returns></returns>
        bool Run(GlobalConfigData globalConfigData);
    }

    public static class Runner
    {
        public static void Start(IRunner runer)
        {
            _runer = runer;

            try
            {
                LoadAndRun();
            }
            catch (Exception e)
            {
                TraceLog.Error(e.Message);
            }
        }

        private static void LoadAndRun()
        {
            ReadGlobalConfig();
            TraceLog.WriteToFile = _config.WriteToLogFile;

            string appName = Process.GetCurrentProcess().MainModule.FileName;
            string[] filelist = Directory.GetFiles(Path.GetDirectoryName(appName), "*.ini");
            Array.Sort(filelist);
            foreach (string filename in filelist)
            {
                try
                {
                    TraceLog.PrintLn("读取账号文件: " + filename);

                    _runer.LoadConfig(filename);

                    for (int i = 0; i < _config.TryTimes; i++)
                    {
                        if (_runer.Run(_config))
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    TraceLog.Error(e.Message);
                }
            }
        }

        private static void ReadGlobalConfig()
        {
            try
            {
                string filename = _appDirectory + "\\" + c_ConfigFile;

                if (!File.Exists(filename))
                {
                    TraceLog.PrintLn("缺少{0}文件，系统加载默认配置.", filename);
                    return;
                }

                _config = GlobalConfigHelper.ReadGlobalConfigData(filename);
            }
            catch (Exception e)
            {
                TraceLog.Error(e.Message);
            }
        }

        #region Member Fields
        private const string c_ConfigFile = "Config.txt";
        private static string _appDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
        private static GlobalConfigData _config = new GlobalConfigData();
        private static IRunner _runer;
        #endregion
    }
}
